<?php
/**
 * +--------------------------------------------------------+
 * @Created by Phpstorm.
 * @Category AdminController.php
 * @Depiction
 * @Author hwy <429208948@qq.com>
 * @Date 2022/4/14  19:16
 * +--------------------------------------------------------+
 */

namespace App\Http\Controllers\Admin\V1;

use App\Models\Permission;
use App\Rules\Mobile;
use App\Services\AdminService;
use App\Util\Routes;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class AdminController extends Controller
{
    /**
     * @var $adminService 管理员服务
     */
    protected $adminService;

    public function __construct(AdminService $adminService)
    {
        $this->adminService = $adminService;
    }

    /**
     * @param Request $request
     * @return JsonResponse
     * @Depiction 管理员列表
     * @Author hwy <429208948@qq.com>
     * @Date 2022/4/15  10:43
     */
    public function index(Request $request)
    {
        $rules = [
            'page'     => ['nullable', 'numeric', 'gte:0'],
            'limit'    => ['nullable', 'numeric', 'gte:1', 'lte:100'],
            'sort'     => ['nullable',],
            'order'    => ['nullable', 'string'],
            'name'     => ['nullable', 'string', 'between:1,32'],
            'email'    => ['nullable', 'string', 'between:1,32'],
            'status'   => ['nullable', 'integer', Rule::in(0, 1)],
            'role_ids' => ['nullable', 'array'],
            'start_at' => ['required_with:end_at', 'date_format:Y-m-d H:i:s', 'before_or_equal:end_at'],
            'end_at'   => ['required_with:start_at', 'date_format:Y-m-d H:i:s', 'after_or_equal:start_at'],
        ];

        $attributes = [
            'page'     => '页数',
            'limit'    => '每页条数',
            'sort'     => '排序字段',
            'order'    => '排序顺序',
            'name'     => '名字',
            'email'    => 'Email',
            'status'   => '状态',
            'role_ids' => '角色',
            'start_at' => '开始时间',
            'end_at'   => '结束时间',
        ];

        $messages = [];

        $validated = $this->validate($request, $rules, $messages, $attributes);

        $data = $this->adminService->getList($validated);

        return $this->responseSuccessData('请求成功!', $data);
    }

    /**
     * @return JsonResponse
     * @Depiction 获取用户信息
     * @Author hwy <429208948@qq.com>
     * @Date 2022/1/7  17:55
     */
    public function getInfo()
    {
        // $user = $this->jwt->user();
        $user = auth('admin')->user();
        if (empty($user)) {
            return $this->responseErrorData();
        }

        $accessedRoutes = (new Routes($user))->routes();

        $roles = $user->roles->mapWithKeys(function ($role, $key) {
            return [$key => $role->id];
        })->prepend('App\Models\Admin\\' . $user->id);

        unset($user->roles);

        // 路由
        $user['accessedRoutes'] = $accessedRoutes;
        // 对应角色
        $user['roles'] = $roles;

        $data = $user;

        return $this->responseSuccessData('请求成功!', $data);

    }

    /**
     * @param Request $request
     * @return JsonResponse
     * @Depiction
     * @Author hwy <429208948@qq.com>
     * @Date 2022/6/7  13:54
     */
    public function show(Request $request)
    {
        $id = $request->post('id', 0);
        if (empty($id)) {
            return $this->responseErrorData('用户不存在！');
        }

        $admin = $this->adminService->getValue($id);

        if ($admin) {
            $admin->roles;
            $roleIds = $admin->roles->mapWithKeys(function ($role, $key) {
                return [$key => $role->id];
            });
            $admin->permissions;
            $permissionIds          = $admin->permissions->mapWithKeys(function ($permission, $key) {
                return [$key => $permission->id];
            });
            $admin['roleIds']       = $roleIds;
            $admin['permissionIds'] = $permissionIds;

            return $this->responseSuccessData('请求成功', $admin);
        }

        return $this->responseErrorData('用户不存在！');

    }

    /**
     * @param Request $request
     * @throws \App\Exceptions\ValidationException
     * @Depiction
     * @Author hwy <429208948@qq.com>
     * @Date 2022/3/25  17:16
     */
    public function create(Request $request)
    {
        $rules      = [
            'name'     => ['required', 'string', 'unique:admins', 'between:5,32'],
            'email'    => ['required', 'string', 'email', 'unique:admins', 'between:5,60'],
            'mobile'   => ['required', 'string', 'unique:admins', 'between:7,15'],
            'password' => ['required', 'string', 'between:6,32'],
            'status'   => ['required', 'integer', Rule::in([0, 1])],
        ];
        $attributes = [
            'name'     => '用户名',
            'email'    => '邮箱',
            'mobile'   => '手机号码',
            'password' => '密码',
            'status'   => '状态值',
        ];
        $messages   = [];

        $validated = $this->validate($request, $rules, $messages, $attributes);

        $this->adminService->create($validated);

        return $this->responseSuccessData('添加成功！');
    }

    /**
     * @param Request $request
     * @return JsonResponse
     * @throws \App\Exceptions\ValidationException
     * @Depiction
     * @Author hwy <429208948@qq.com>
     * @Date 2022/3/25  17:49
     */
    public function update(Request $request)
    {
        $user = $this->adminService->getValue($request->post('id', 0));
        if (empty($user)) {
            $this->responseErrorData('用户不存在');
        }

        $rules      = [
            'id'       => ['required', 'integer',],
            'name'     => ['required', 'string', Rule::unique('admins')->ignore($user), 'between:6,32'],
            'email'    => ['required', 'string', 'email', Rule::unique('admins')->ignore($user), 'between:6,60'],
            'mobile'   => ['required', 'string', new Mobile(), Rule::unique('admins')->ignore($user), 'between:5,15'],
            'password' => ['nullable', 'string', 'between:6,32'],
            'status'   => ['required', 'integer', Rule::in([0, 1])],
        ];
        $attributes = [
            'name'     => '用户名',
            'email'    => '邮箱',
            'mobile'   => '手机',
            'password' => '密码',
            'status'   => '状态值',
        ];
        $messages   = [];

        $validated = $this->validate($request, $rules, $messages, $attributes);

        $this->adminService->update($validated);

        return $this->responseSuccessData('修改成功！');
    }

    /**
     * @param Request $request
     * @return JsonResponse
     * @Depiction
     * @Author hwy <429208948@qq.com>
     * @Date 2022/3/25  17:52
     */
    public function delete(Request $request)
    {
        $id   = $request->post('id', 0);
        $user = $this->adminService->getValue($id);

        if ($user) {
            $user->delete();
            return $this->responseSuccessData('删除成功！');
        }

        return $this->responseErrorData('删除失败！');
    }

    /**
     * @param Request $request
     * @throws \App\Exceptions\ValidationException
     * @Depiction
     * @Author hwy <429208948@qq.com>
     * @Date 2022/3/26  16:25
     */
    public function syncPermissions(Request $request)
    {
        $rules      = [
            'id'          => ['required', 'integer', 'exists:admins'],
            'permissions' => ['array'],
        ];
        $attributes = [
            'id'          => '用户ID',
            'permissions' => '权限/目录',
        ];
        $messages   = [];

        $validated = $this->validate($request, $rules, $messages, $attributes);

        $user = $this->adminService->getValue($validated['id']);

        $permissions = isset($validated['permissions']) ? Permission::whereIn('id', $validated['permissions'])->get() : [];

        $user->syncPermissions($permissions);

        return $this->responseSuccessData('修改成功！');

    }

}
